package weixin.dao;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import weixin.WechatParam;
import weixin.utils.BaseUtils;
import weixin.utils.RequestUtils;



@Component
public class WechatDao {
	private static Logger logger=Logger.getLogger(WechatDao.class);
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	private static ObjectMapper objectMapper=new ObjectMapper();
	
	/**
	 *@note: 更新系统access_token
	 *@date: 2017年7月4日 下午10:44:06
	 */
	public void updateAccess_token(){
		long originalTime=WechatParam.getAccess_token_time();
		if(!WechatParam.checkTimeAccessToken(originalTime)){
			String result=WechatDao.getWechatServerAccess_token();
			updateAccess_token(result);
		}
	}
	/**
	 *@note: 更新	access_token到数据库
	 *@date: 2017年4月22日 下午1:30:09
	 *@WechatParam access_token
	 */
	public void updateAccess_token(String access_token){
		Date date=new Date();
		WechatParam.setAccess_token(access_token);
		WechatParam.setAccess_token_time(date.getTime());
		jdbcTemplate.update("UPDATE wx_account SET access_token='"+access_token+"',access_token_update_time="+date);
	}
	
	/**
	 *@note: 从微信服务器获取	Access_token
	 *@date: 2017年4月22日 下午11:00:19
	 *@return
	 */
	@SuppressWarnings("unchecked")
	public static String getWechatServerAccess_token(){
    	//数据库没有，走下面流程
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+WechatParam.getAppId()+"&secret="+WechatParam.getAppsecret();
        String resultJson = RequestUtils.doGet(url);// 从微信服务器获取值
        Map<String, Object> resultMap=null;
        try
        {
            resultMap =objectMapper.readValue(resultJson, Map.class);
        }
        catch (Exception e)
        {
            logger.error("getwxAccess_token:"+e.getMessage());
        }
        if (resultMap.get("errcode") != null)
        {
            logger.info("获取wxAccess_token失败：" + resultJson);
        }
    	return resultMap.get("access_token").toString();
    }
	
	
	/**
	 *@note: 更新系统Api_ticket
	 *@date: 2017年7月4日 下午10:45:10
	 */
	public void updateApi_ticket(){
		long originalTime=WechatParam.getApi_ticket_time();
		if(!WechatParam.checkTimeApiTicket(originalTime)){
			String result=WechatDao.getWechatServerApi_ticket();
			updateApi_ticket(result);
		}
	}
	/**
	 *@note: 更新	Api_ticket到数据库
	 *@date: 2017年7月4日 下午10:43:37
	 *@param api_ticket
	 */
	public void updateApi_ticket(String api_ticket){
		Date date=new Date();
		WechatParam.setApi_ticket(api_ticket);
		WechatParam.setApi_ticket_time(date.getTime());
		jdbcTemplate.update("UPDATE wx_account SET jsapi_ticket='"+api_ticket+"',jsapi_ticket_update_time="+date);
	}
	
	
	/**
	 *@note: 从微信服务器获取	Api_ticket
	 *@date: 2017年4月22日 下午11:01:49
	 *@return
	 */
	@SuppressWarnings("unchecked")
	public static String getWechatServerApi_ticket(){
    	//数据库没有，走下面流程
    	String url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+BaseUtils.getAccess_token()+"&type=jsapi";
        String resultJson = RequestUtils.doGet(url);// 从微信服务器获取值
        Map<String, Object> resultMap=null;
        try
        {
            resultMap =objectMapper.readValue(resultJson, Map.class);
        }
        catch (Exception e)
        {
            logger.error("getwxApi_ticket:"+e.getMessage());
        }
        if (resultMap.get("errcode").equals("0"))
        {
            logger.info("获取getwxApi_ticket失败：" + resultJson);
        }
    	return resultMap.get("ticket").toString();
    }
	
	
	/**
	 *@note: 初始化微信内容	
	 *@date: 2017年7月4日 下午10:11:53
	 */
	public void initWechatParam(){
		List<Map<String, Object>> resultList=jdbcTemplate.queryForList("select * from wx_account");
		if(resultList!=null&&resultList.size()>0){
			Map<String,Object> result=resultList.get(0);
			WechatParam.setAppId(result.get("appID").toString());;
			WechatParam.setAppsecret(result.get("appsecret").toString());
			WechatParam.setAccount(result.get("account").toString());;
			WechatParam.setToken(result.get("token").toString());;
			WechatParam.setAccess_token(result.get("access_token")==null?null:result.get("access_token").toString());
			WechatParam.setAccess_token_time(result.get("access_token_update_time")==null?0:Timestamp.valueOf(result.get("access_token_update_time").toString()).getTime());
			WechatParam.setApi_ticket(result.get("jsapi_ticket")==null?null:result.get("jsapi_ticket").toString());
			WechatParam.setApi_ticket_time(result.get("jsapi_ticket_update_time")==null?0:Timestamp.valueOf(result.get("jsapi_ticket_update_time").toString()).getTime());
			
		}
		else
		{
			throw new NullPointerException("未配置公众号");
		}
	}
	

	
}
